package com.fxwater.websocket.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.fxwater.websocket.domain.ScheduledSqlInfo;
import com.fxwater.websocket.mapper.ScheduledSqlInfoMapper;
import com.fxwater.websocket.service.IScheduledSqlInfoService;
import com.fxwater.websocket.util.KeyUtil;
import com.fxwater.websocket.util.SpringBeanFinder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.sql.ResultSet;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: 王明朝
 * @Date: 2019/8/17 12:56
 */
@Service
public class ScheduledSqlInfoServiceImpl implements IScheduledSqlInfoService {

    private List<ScheduledSqlInfo> scheduledSqlInfos = null;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private ScheduledSqlInfoMapper scheduledSqlInfoMapper;


    private RedisTemplate<String, Serializable> redisTemplate;

    Logger logger = LoggerFactory.getLogger(ScheduledSqlInfoServiceImpl.class);



    @Override
    public void executeAllSqlAndStore() {
        logger.info("-----------------------------------开始缓存第一场景数据----------------------------");
        try {
            if(scheduledSqlInfos==null){
                initScheduledSqlInfoList();
            }
            if(redisTemplate==null){
                redisTemplate = SpringBeanFinder.findBean("stringRedisTemplate");
            }
            if(CollectionUtil.isNotEmpty(scheduledSqlInfos)){
                scheduledSqlInfos.forEach(scheduledSqlInfo -> {
                    Object data = null;
                    String sceneId = scheduledSqlInfo.getSceneId();
                    String groupId = scheduledSqlInfo.getGroupId();
                    String keyId =  scheduledSqlInfo.getKeyId();
                    String redisKey = KeyUtil.getRedisKey(sceneId,groupId,keyId);
                    logger.info("第一场景，开始缓存键值为{}的数据！",redisKey);
                    switch (scheduledSqlInfo.getReturnType().toUpperCase()){
                        case "LIST":
                            List<Map<String,Object>> list  = jdbcTemplate.queryForList(scheduledSqlInfo.getSqlContent());
                            data = list;
                            redisTemplate.opsForValue().set(redisKey, JSONUtil.toJsonStr(JSONUtil.parse(data)));
                            logger.info("第一场景，开始缓存键值为{}的数据{}！",redisKey,data);
                            break;
                        case "MAP":
                            List<Map<String,Object>> maps = jdbcTemplate.queryForList(scheduledSqlInfo.getSqlContent());
                            if(CollectionUtil.isNotEmpty(maps)){
                                data = maps.get(0);
                                redisTemplate.opsForValue().set(redisKey,JSONUtil.toJsonStr(JSONUtil.parse(data)));
                            }
                            logger.info("第一场景，开始缓存键值为{}的数据{}！",redisKey,data);
                            break;
                        case "DOUBLE":
                            Double doubleValue = jdbcTemplate.query(scheduledSqlInfo.getSqlContent(),(ResultSet resultSet) -> resultSet.getDouble(0));
                            data = doubleValue;
                            logger.info("第一场景，开始缓存键值为{}的数据{}！",redisKey,data);
                            redisTemplate.opsForValue().set(redisKey,String.valueOf(data));
                            break;
                        case "INT":
                            Integer intValue = jdbcTemplate.query(scheduledSqlInfo.getSqlContent(),(ResultSet resultSet) -> resultSet.getInt(0));
                            data = intValue;
                            logger.info("第一场景，开始缓存键值为{}的数据{}！",redisKey,data);
                            redisTemplate.opsForValue().set(redisKey,String.valueOf(data));
                            break;
                       default :
                           List<Map<String,Object>> dataMaps = jdbcTemplate.queryForList(scheduledSqlInfo.getSqlContent());
                           if(CollectionUtil.isNotEmpty(dataMaps)){
                               if(dataMaps.size()==1){
                                   data = dataMaps.get(0);
                               } else {
                                   data = dataMaps;
                               }
                           } else {
                               data = null;
                           }
                           logger.info("第一场景，开始缓存键值为{}的数据{}！",redisKey,data);
                           redisTemplate.opsForValue().set(redisKey,JSONUtil.toJsonStr(JSONUtil.parse(data)));
                           break;
                    }

                });
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
        }
        logger.info("-----------------------------------结束缓存第一场景数据----------------------------");
    }

    private void initScheduledSqlInfoList() {
        scheduledSqlInfos = scheduledSqlInfoMapper.selectAii();
    }
}
